package com.yuan.dao;

import com.yuan.pojo.LinkMan;
import com.yuan.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class LinkManDao {
    private QueryRunner queryRunner= new QueryRunner(DruidUtil.getDataSource());

    public List<LinkMan> findAll() throws Exception {
        return  queryRunner.query("select * from linkman",new BeanListHandler<>(LinkMan.class));
    }

    public void add(LinkMan linkMan) throws Exception {
        queryRunner.update("insert into linkman values(null,?,?,?,?,?,?)",linkMan.getName(),linkMan.getSex(),
        linkMan.getAge(),linkMan.getAddress(),linkMan.getQq(),linkMan.getEmail());
    }

    public void delete(Integer id) throws Exception {
        queryRunner.update("delete from linkman where id =?",id);
    }

    public LinkMan findOne(Integer id) throws Exception {
        LinkMan linkMan = queryRunner.query("select * from linkman where id =?", new BeanHandler<>(LinkMan.class), id);
        return linkMan;

    }

    public void update(LinkMan linkMan) throws Exception {
        queryRunner.update("update linkman set name=?,sex=?,age=?,address=?,qq=?,email=? where id =?",
                linkMan.getName(),linkMan.getSex(),linkMan.getAge(),linkMan.getAddress(),linkMan.getQq(),linkMan.getEmail(),linkMan.getId());
    }

    public Long findTotalSize() throws Exception {
        return (Long) queryRunner.query("select count(*) from linkman",new ScalarHandler());
    }

    public List<LinkMan> findPageList(Long currentPage, Long pageSize) throws Exception {
        return queryRunner.query("select * from linkman limit ?,?",new BeanListHandler<>(LinkMan.class),(currentPage-1)*pageSize,pageSize);
    }
}
